<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="统计日期" prop="statDate">
              <el-date-picker clearable
                v-model="queryParams.statDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择统计日期"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>服务质量统计分析</span>
              <el-button type="primary" size="small" @click="handleQuery">
                <el-icon><Refresh /></el-icon> 刷新数据
              </el-button>
            </div>
          </template>
          <div class="stats-cards">
            <div class="stat-card bg-blue">
              <div class="stat-value">{{ statisticsData.totalServices }}</div>
              <div class="stat-label">服务总数</div>
            </div>
            <div class="stat-card bg-green">
              <div class="stat-value">{{ statisticsData.completedServices }}</div>
              <div class="stat-label">已完成服务</div>
            </div>
            <div class="stat-card bg-orange">
              <div class="stat-value">{{ statisticsData.totalServices - statisticsData.completedServices }}</div>
              <div class="stat-label">未完成服务</div>
            </div>
            <div class="stat-card bg-red">
              <div class="stat-value">{{ Math.round((statisticsData.completedServices / statisticsData.totalServices) * 100) || 0 }}%</div>
              <div class="stat-label">服务完成率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>服务类型分布</span>
            </div>
          </template>
          <div id="servicePieChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 表格已隐藏 -->
    <!-- 添加或修改服务质量统计对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="serviceQualityStatisticsFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="统计日期" prop="statDate">
          <el-date-picker clearable
            v-model="form.statDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择统计日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="统计月份" prop="statMonth">
          <el-input v-model="form.statMonth" placeholder="请输入统计月份" />
        </el-form-item>
        <el-form-item label="统计年份" prop="statYear">
          <el-input v-model="form.statYear" placeholder="请输入统计年份" />
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceType">
          <el-select v-model="form.serviceType" placeholder="请选择服务类型">
            <el-option
                v-for="dict in sys_fwlx"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务总数" prop="totalServices">
          <el-input v-model="form.totalServices" placeholder="请输入服务总数" />
        </el-form-item>
        <el-form-item label="已完成服务数" prop="completedServices">
          <el-input v-model="form.completedServices" placeholder="请输入已完成服务数" />
        </el-form-item>
        <el-form-item label="已取消服务数" prop="canceledServices">
          <el-input v-model="form.canceledServices" placeholder="请输入已取消服务数" />
        </el-form-item>
        <el-form-item label="平均响应时间(分钟)" prop="avgResponseTime">
          <el-input v-model="form.avgResponseTime" placeholder="请输入平均响应时间(分钟)" />
        </el-form-item>
        <el-form-item label="平均完成时间(分钟)" prop="avgCompletionTime">
          <el-input v-model="form.avgCompletionTime" placeholder="请输入平均完成时间(分钟)" />
        </el-form-item>
        <el-form-item label="平均满意度评分(1-5分)" prop="avgSatisfactionScore">
          <el-input v-model="form.avgSatisfactionScore" placeholder="请输入平均满意度评分(1-5分)" />
        </el-form-item>
        <el-form-item label="投诉数量" prop="complaintCount">
          <el-input v-model="form.complaintCount" placeholder="请输入投诉数量" />
        </el-form-item>
        <el-form-item label="表扬数量" prop="praiseCount">
          <el-input v-model="form.praiseCount" placeholder="请输入表扬数量" />
        </el-form-item>
        <el-form-item label="改进建议" prop="improvementSuggestions">
            <el-input v-model="form.improvementSuggestions" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ServiceQualityStatistics" lang="ts">
import { listServiceQualityStatistics, getServiceQualityStatistics, delServiceQualityStatistics, addServiceQualityStatistics, updateServiceQualityStatistics } from '@/api/nursing/serviceQualityStatistics';
import { ServiceQualityStatisticsVO, ServiceQualityStatisticsQuery, ServiceQualityStatisticsForm } from '@/api/nursing/serviceQualityStatistics/types';
import * as echarts from 'echarts';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_fwlx } = toRefs<any>(proxy?.useDict('sys_fwlx'));

const serviceQualityStatisticsList = ref<ServiceQualityStatisticsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const serviceQualityStatisticsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ServiceQualityStatisticsForm = {
  statId: undefined,
  statDate: undefined,
  statMonth: undefined,
  statYear: undefined,
  serviceType: undefined,
  totalServices: undefined,
  completedServices: undefined,
  canceledServices: undefined,
  avgResponseTime: undefined,
  avgCompletionTime: undefined,
  avgSatisfactionScore: undefined,
  complaintCount: undefined,
  praiseCount: undefined,
  improvementSuggestions: undefined,
  remarks: undefined,
}
const data = reactive<PageData<ServiceQualityStatisticsForm, ServiceQualityStatisticsQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    statDate: undefined,
    params: {
      realtime: '1' // 添加realtime参数，获取实时统计数据
    }
  },
  rules: {
    statId: [
      { required: true, message: "统计ID不能为空", trigger: "blur" }
    ],
    statDate: [
      { required: true, message: "统计日期不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 统计数据
const statisticsData = ref({
  totalServices: 0,
  completedServices: 0,
  canceledServices: 0,
  avgResponseTime: 0,
  avgCompletionTime: 0,
  avgSatisfactionScore: 0,
  complaintCount: 0,
  praiseCount: 0
});

// 图表实例
let servicePieChartInstance: echarts.ECharts | null = null;

/** 查询服务质量统计列表 */
const getList = async () => {
  loading.value = true;

  try {
    // 确保params对象存在
    if (!queryParams.value.params) {
      queryParams.value.params = { realtime: '1' };
    } else {
      queryParams.value.params.realtime = '1';
    }

    const res = await listServiceQualityStatistics(queryParams.value);
    serviceQualityStatisticsList.value = res.rows;
    total.value = res.total;

    // 如果有数据，更新统计数据
    if (res.rows && res.rows.length > 0) {
      const data = res.rows[0];

      // 更新统计数据
      statisticsData.value = {
        totalServices: data.totalServices || 0,
        completedServices: data.completedServices || 0,
        canceledServices: data.canceledServices || 0,
        avgResponseTime: data.avgResponseTime || 0,
        avgCompletionTime: data.avgCompletionTime || 0,
        avgSatisfactionScore: data.avgSatisfactionScore || 0,
        complaintCount: data.complaintCount || 0,
        praiseCount: data.praiseCount || 0
      };

      // 更新顶部卡片显示的数据
      updateStatsSummary();

      // 初始化图表
      nextTick(() => {
        initServicePieChart();
      });
    }
  } catch (error) {
    console.error('获取统计数据失败', error);
    proxy?.$modal.msgError('获取统计数据失败');
  } finally {
    loading.value = false;
  }
}

/** 更新顶部卡片显示的数据 */
const updateStatsSummary = () => {
  // 更新顶部卡片中的标签
  const qualityHeader = document.querySelector('.quality-header el-tag');
  if (qualityHeader) {
    qualityHeader.textContent = `${statisticsData.value.avgSatisfactionScore}/5.0`;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  serviceQualityStatisticsFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ServiceQualityStatisticsVO[]) => {
  ids.value = selection.map(item => item.statId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加服务质量统计";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ServiceQualityStatisticsVO) => {
  reset();
  const _statId = row?.statId || ids.value[0]
  try {
    const res = await getServiceQualityStatistics(_statId);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改服务质量统计";
  } catch (error) {
    console.error('获取服务质量统计详情失败', error);
    proxy?.$modal.msgError('获取服务质量统计详情失败');
  }
}

/** 提交按钮 */
const submitForm = () => {
  serviceQualityStatisticsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.statId) {
        await updateServiceQualityStatistics(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addServiceQualityStatistics(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ServiceQualityStatisticsVO) => {
  const _statIds = row?.statId || ids.value;
  try {
    await proxy?.$modal.confirm('是否确认删除服务质量统计编号为"' + _statIds + '"的数据项？');
    await delServiceQualityStatistics(_statIds);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  } catch (error) {
    console.error('删除服务质量统计失败', error);
  } finally {
    loading.value = false;
  }
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('nursing/serviceQualityStatistics/export', {
    ...queryParams.value
  }, `serviceQualityStatistics_${new Date().getTime()}.xlsx`)
}

/** 初始化服务类型饼图 */
const initServicePieChart = () => {
  const chartDom = document.getElementById('servicePieChart');
  if (!chartDom) {
    console.error('找不到饼图DOM元素');
    return;
  }

  // 如果已经存在图表实例，先销毁
  if (servicePieChartInstance) {
    servicePieChartInstance.dispose();
  }

  servicePieChartInstance = echarts.init(chartDom);

  // 服务类型数据
  const serviceTypes = [
    { name: '饮食服务', value: 14 },
    { name: '特殊护理服务', value: 10 },
    { name: '紧急需求服务', value: 6 }
  ];

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}个 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: serviceTypes.map(item => item.name)
    },
    series: [
      {
        name: '服务类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {d}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: serviceTypes
      }
    ]
  };

  servicePieChartInstance.setOption(option);

  // 监听窗口变化，调整图表大小
  window.addEventListener('resize', () => {
    servicePieChartInstance && servicePieChartInstance.resize();
  });
}

onMounted(() => {
  getList();
});

onUnmounted(() => {
  window.removeEventListener('resize', () => {});
});
</script>

<style scoped>
.quality-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
}

.stats-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  justify-content: space-between;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1 1 calc(25% - 15px);
  min-width: calc(25% - 15px);
  border-radius: 10px;
  padding: 20px;
  text-align: center;
  color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 10px;
}

.stat-label {
  font-size: 14px;
}

.bg-blue {
  background: linear-gradient(135deg, #409EFF, #64B5F6);
}

.bg-green {
  background: linear-gradient(135deg, #67C23A, #9ED86E);
}

.bg-orange {
  background: linear-gradient(135deg, #E6A23C, #FFB74D);
}

.bg-red {
  background: linear-gradient(135deg, #F56C6C, #FF8A80);
}

.mt-4 {
  margin-top: 20px;
}

.mb-4 {
  margin-bottom: 20px;
}
</style>
